from rest_framework.serializers import ModelSerializer
from util.typing import RestFrameWorkModelSerializerTyping
from .models import Region
from rest_framework import serializers
from rest_framework.request import HttpRequest


class RegionSerializer(ModelSerializer):
    user_id = serializers.IntegerField(
        source='user.id',
        write_only=True,
        required=False,
    )




    class Meta(RestFrameWorkModelSerializerTyping):
        model = Region
        fields = ['id','name','region_set','user_id']
        # exclude = ['user']
        depth = 1

    def create(self, validated_data):
        request: HttpRequest = self.context['request']
        parent = None
        if request.data.get('parent_region'):
            parent = Region.objects.filter(id=request.data['parent_region']).first()
        validated_data['user_id'] = request.user.id
        validated_data['parent_region'] = parent
        return super().create(validated_data)

    def update(self, instance, validated_data):
        request: HttpRequest = self.context['request']
        validated_data['user_id'] = request.user.id
        return super().update(instance, validated_data)
